﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;
using Common.Library;
using Common.Utilities;
using OnlineVideos.Data;
using InsertIntoDataBase;
using OnlineVideos.UI;
using PicasaMobileInterface;
using Social_Celebrities.Views;
using Newtonsoft.Json.Linq;

namespace Social_Celebrities.Views
{
    public partial class Browser : PhoneApplicationPage
    {
        string Parameter = string.Empty;
        string Link = string.Empty;
        string link_mod = string.Empty;
        string link_nc = string.Empty;        
        public Browser()
        {
            InitializeComponent();
            Loaded += Browser_Loaded;
        }

        void Browser_Loaded(object sender, RoutedEventArgs e)
        {            
            if (string.IsNullOrEmpty(AppSettings.FaceBookAccessToken))
            {
                NavigationService.Navigate(new Uri("/Views/FacebookLoginPage.xaml", UriKind.Relative));
            }
            else
            {
                MyBrowser.Navigate(new Uri("https://www.facebook.com/search.php?q=" + Parameter, UriKind.RelativeOrAbsolute));
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (NavigationContext.QueryString.TryGetValue("Parameter", out Parameter))
            {
            }
        }
        private void MyBrowser_LoadCompleted_1(object sender, NavigationEventArgs e)
        {
             Addrbar.Text = e.Uri.AbsoluteUri;
             Link = Addrbar.Text; 
            MessageBoxResult result=default(MessageBoxResult);
            if (!Link.Contains("search.php") && !Link.Contains("results.php"))
            {
                result = MessageBox.Show("Confirm this Celebrity?", "", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    try
                    {
                        //Addrbar.Text = e.Uri.AbsoluteUri;
                        //Link = Addrbar.Text;
                        WebClient wclnt = new WebClient();
                        if (!string.IsNullOrEmpty(Link))
                        {
                            wclnt.DownloadStringAsync(new Uri(Link));
                            wclnt.DownloadStringCompleted += wclnt_DownloadStringCompleted;
                        }
                        AppSettings.BackgroundAgenError = "Browser_Loaded Method on Browser.xaml.cs Completed Successfully";
                    }
                    catch (Exception ex)
                    {
                        //Exceptions.SendErrortoMail("Exception at MyBrowser_LoadCompleted_1 Method in Browser.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                        Exceptions.SaveOrSendExceptions("Exception at Browser LoadCompleted Method in Browser.xaml.cs file", ex);
                        AppSettings.BackgroundAgenError = ex.Message;
                    }
                }
                else
                {
                    MyBrowser.Navigate(new Uri("https://www.facebook.com/search.php?q=" + Parameter, UriKind.RelativeOrAbsolute));
                }
            }

        }

        void wclnt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                link_nc = e.Result;
                if (!Link.Contains("search.php") && !Link.Contains("results.php"))
                {
                    if (!string.IsNullOrEmpty(AppSettings.FaceBookAccessToken))
                    {
                        if (Link.StartsWith("https://www.facebook.com/profile.php?"))
                        {
                            string id = Link.Substring(Link.LastIndexOf("id=") + 3);
                            Constants.FacebookNID = id;
                            Dispatcher.BeginInvoke(() =>
                            {
                                NavigationService.GoBack();
                            });
                        }
                        else
                        {
                            Facebook.FacebookClient face = new Facebook.FacebookClient(AppSettings.FaceBookAccessToken);
                            face.GetAsync(Link);
                            face.GetCompleted += face_GetCompleted;
                        }
                    }

                    //link_mod = Link.Replace("www", "graph");
                    //WebClient webclnt = new WebClient();
                    //if (!string.IsNullOrEmpty(link_mod))
                    //{
                    //    webclnt.DownloadStringAsync(new Uri(link_mod));
                    //    webclnt.DownloadStringCompleted += webclnt_DownloadStringCompleted;
                    //}
                }
                AppSettings.BackgroundAgenError = "wclnt_DownloadStringCompleted Method in Browser.xaml.cs file Completed Successfully!!!";
            }
            catch (Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at wclnt_DownloadStringCompleted Method in Browser.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at wclnt_DownloadStringCompleted Method in Browser.xaml.cs file", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        void face_GetCompleted(object sender, Facebook.FacebookApiEventArgs e)
        {
            if (e.Error == null)
            {
                var result = (IDictionary<string, object>)e.GetResultData();
                string id = (string)result["id"];
                if (id.StartsWith("https://www.facebook.com/groups/"))
                    id = id.Replace("https://www.facebook.com/groups/", "").Replace("/", "");
                Constants.FacebookNID = id;
                Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.GoBack();
                });
            }
            else
            {
                Constants.FacebookNID = string.Empty;
                Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.GoBack();
                });
            }
        }

        //void webclnt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        //{
        //    try
        //    {
        //        var link_final = e.Result;
        //        if (link_final.Contains("username"))
        //        {
        //            var item = Regex.Split(e.Result, ",")[0].Replace(@"{""id"":", "").Replace(@"""", "");
        //            Constants.FacebookNID = item;
        //            NavigationService.GoBack();
        //        }
        //        AppSettings.BackgroundAgenError = "webclnt_DownloadStringCompleted Method in Browser.xaml.cs file Completed Successfully !!!!";
        //    }
        //    catch (Exception ex)
        //    {
        //        Exceptions.SendErrortoMail("Exception at webclnt_DownloadStringCompleted Method in Browser.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
        //        Exceptions.SaveOrSendExceptions("Exception at webclnt_DownloadStringCompleted Method in Browser.xaml.cs file", ex);
        //        AppSettings.BackgroundAgenError = ex.Message;
        //    }
        //}
    }
}